package service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

public class JPAUtil {
	
	protected static EntityManager em;
	
	public EntityManager getEntityManager() {
		if(em == null){
			em = buildEntityManager();
		}
		return em;
	}

	public EntityManager buildEntityManager(){
		EntityManagerFactory emf;
		emf = Persistence.createEntityManagerFactory("HRUnit");
		em = emf.createEntityManager();
		return em;
	}
	
	public <T> List<T> findAll(Class<T> entity){
		em = getEntityManager();
		TypedQuery<T> tq = em.createNamedQuery(entity.getSimpleName() + ".findAll", entity);
		return tq.getResultList();
	}
	
	public <T> T findByKey(Class<T> entity, Object primaryKey){
		em = getEntityManager();
		return em.find(entity, primaryKey);
	}

}
